package cn.zftt.common;

import cn.zftt.common.annotation.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author zhangfeng
 */
@Aspect
@Component
@Order(1)
public class DataSourceAspect {

    @Pointcut("@annotation(cn.zftt.common.annotation.DataSource)")
    public void dataSourcePointCut() {
    }

    @Before("dataSourcePointCut()")
    public void before(JoinPoint joinPoint) throws Exception {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            String dataSourceName = dataSource.value();
            if (StringUtils.isNotEmpty(dataSourceName)) {
                DynamicDataSource.setDataSource(dataSourceName);
            }
        } else
            throw new Exception("没有设置数据源");
    }

    @After("dataSourcePointCut()")
    public void after(JoinPoint joinPoint) {
        DynamicDataSource.clearDataSource();
    }
}
